import os
import sys

path = os.path.dirname(__file__)
sys.path.append(os.path.join(path, ".."))

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from conf.config import MYSQL_CONFIG

mysql_host = MYSQL_CONFIG['host']
mysql_port = MYSQL_CONFIG['port']
mysql_user = MYSQL_CONFIG['user']
mysql_password = MYSQL_CONFIG['password']
mysql_db = MYSQL_CONFIG['db']

# 连接MySQL需要用到的用户名，密码，主机，端口，数据库名
DB_URI = f'mysql+pymysql://{mysql_user}:{mysql_password}@{mysql_host}:{mysql_port}/{mysql_db}?charset=utf8mb4'
ENGINE = create_engine(
    DB_URI,
    max_overflow=10,  # 超过连接池大小外最多创建的连接
    encoding='utf-8',  # 默认为 utf-8
    pool_size=30,  # -- 在连接池中保持打开的连接数   设置为0表示没有限制
    pool_timeout=30,  # -- 在放弃从池中获取连接之前等待的秒数
)


def validate_connection():
    """测试连接是否正常"""
    try:
        with ENGINE.connect() as conn:
            result = conn.execute('select 1')
            return bool(result)
    except (Exception,) as e:
        return False


DBSession = sessionmaker(bind=ENGINE)
SESSION = DBSession()

BASE = declarative_base(bind=ENGINE)
VALIDATE_CONNECT = validate_connection()
